<template>
  <div
    class="app-container"
    v-if="
      $store.state.user.userLevel === null ||
      $store.state.user.userLevel === '1' ||
      $store.state.user.userLevel === '2'
    "
  >
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col
          :span="5"
          v-if="['', null].includes($store.state.user.userLevel)"
        >
          <el-form-item label="油企名称" prop="enterpriseId" size="small">
            <el-select
              style="width: 180px"
              v-model="queryParams.enterpriseId"
              :clearable="true"
              filterable
              placeholder="请选择油企"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="支付单号" prop="payOrder">
            <el-input
              v-model="queryParams.payOrder"
              placeholder="请输入支付单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 150px"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="会员编号" prop="openingMode">
            <el-input
              v-model="queryParams.memberCode"
              placeholder="请输入会员编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="5">
          <el-form-item
            label="会员手机号"
            style="white-space: nowrap"
            prop="mobilePhone"
          >
            <el-input
              v-model="queryParams.mobilePhone"
              placeholder="请输入会员手机号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 150px; padding-left: 10px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="开通时间" prop="beginTime">
            <el-date-picker
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="queryParamsKai"
              style="width: 150px"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择开始时间"
              @change="changeDatetimerange"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="到期时间" prop="beginTime">
            <el-date-picker
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="queryParamsJie"
              style="width: 150px"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择开始时间"
              @change="changeQueryParamsJie"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="global_el_rowStyle">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          type="primary"
          plain
          >重置</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['customer:detail:add']"
          >新增</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['customer:detail:edit']"
          >修改</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['customer:detail:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['customer:detail:export']"
          >导出</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <!-- <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>
    <el-table
      stripe
      v-loading="loading"
      :data="detailList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column
        label="油企名称"
        align="left"
        prop="enterpriseName"
        v-if="['', null].includes($store.state.user.userLevel)"
      />
      <el-table-column label="支付单号" align="left" prop="payOrder" />
      <el-table-column label="会员编号" align="left" prop="memberCode" />
      <el-table-column label="会员手机号" align="left" prop="mobilePhone" />
      <el-table-column label="昵称" align="left" prop="blogNickName" />
      <!-- <el-table-column label="会员登记" align="left" prop="" /> -->
      <el-table-column label="特权名称" align="left">
        <template slot-scope="{ row }">
          {{ row.showName ? row.showName : row.superName }}
        </template>
      </el-table-column>
      <el-table-column label="积分倍数" align="left" prop="multiple" />
      <el-table-column label="开通方式" align="left" prop="openingModeName" />
      <el-table-column label="金额" align="left" prop="amt" />
      <!-- <el-table-column label="类型" align="left" prop="" >
        <template slot-scope="scope">
          <span v-if="1">{{ scope }}</span>
          <span v-else>{{ scope }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="left" prop="enableName" />
      <el-table-column label="订单状态" align="left">
        <template slot-scope="{ row }">
          {{
            row.status === "1" ? "已支付" : row.status === "3" ? "已退款" : ""
          }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="支付金额（元）" align="left" prop="" /> -->
      <el-table-column label="开通时间" align="left" prop="beginDate" />
      <el-table-column label="到期时间" align="left" prop="endDate" />
      <el-table-column
        label="开票状态"
        align="left"
        prop="invoiceStatus"
        :formatter="invoiceStatusFotmat"
      />

      <!-- <el-table-column label="立减活动" align="left" prop="activityName" />
      <el-table-column label="积分倍数" align="left" prop="multiple" />
      <el-table-column label="开通方式" align="left" prop="openingModeName" />
      <el-table-column label="状态" align="left" prop="enableName" />
      <el-table-column label="创建人" align="left" prop="creatby" />
      <el-table-column
        label="创建日期"
        align="left"
        prop="createdate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-col :span="1.5" style="margin-right: 10px">
              <el-button
                type="text"
                size="small"
                @click="recordBilling(scope.row)"
                >开票记录</el-button
              ></el-col
            >
            <el-col :span="1.5" style="margin-right: 10px" v-show="true">
              <el-button
                :disabled="scope.row.status == '3'"
                type="text"
                size="small"
                @click="handleRefund(scope.row)"
                >退款</el-button
              ></el-col
            >
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="支付单号" prop="payOrder">
          <el-input v-model="form.payOrder" placeholder="请输入支付单号" />
        </el-form-item>
        <el-form-item label="开始时间" prop="beginDate">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.beginDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="0手动添加，1线上添加" prop="openingMode">
          <el-input
            v-model="form.openingMode"
            placeholder="请输入0手动添加，1线上添加"
          />
        </el-form-item>
        <el-form-item label="0生效，1停用" prop="enable">
          <el-input v-model="form.enable" placeholder="请输入0生效，1停用" />
        </el-form-item>
        <el-form-item label="创建人" prop="creatby">
          <el-input v-model="form.creatby" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建日期" prop="createdate">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.createdate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择创建日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="来源于app_user_super主键" prop="superId">
          <el-input
            v-model="form.superId"
            placeholder="请输入来源于app_user_super主键"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 开票记录 -->
    <InvoiceRecord
      :invoiceDialog.sync="invoiceDialog"
      :currentRowData="currentRowData"
    ></InvoiceRecord>
  </div>
  <div v-else>您暂无权限查看</div>
</template>

<script>
import { timeComparison } from "@/utils/timeConversion";
import InvoiceRecord from "./invoice_record.vue";
import { enterpriseList } from "@/api/station/order";
import {
  listDetail,
  listDetail2,
  exportDetail2,
  getDetail,
  delDetail,
  addDetail,
  updateDetail,
  exportDetail,
  refundDetail,
} from "@/api/station/detail";

export default {
  name: "Detail",
  components: { InvoiceRecord },
  data() {
    return {
      invoiceDialog: false, // 开票记录弹框
      currentRowData: {}, // 当前选中行数据

      // 开通时间选择值
      queryParamsKai: null,
      // 结束
      queryParamsJie: null,
      // 油企
      enterpriseList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      detailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        // 开始
        beBeginTime: null,
        beEndTime: null,
        // 到期时间
        enBeginTime: null,
        enEndTime: null,

        mobilePhone: null,
        pageNum: 1,
        pageSize: 10,
        payOrder: null,

        openingMode: null,
        enable: null,
        creatby: null,
        createdate: null,
        memberCode: null,
        superId: null,
        mobilePhone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getEnterpriseList();
    this.getList();
  },
  methods: {
    //退款
    async handleRefund(row) {
      let tip;
      const date = new Date(row.endDate);
      const status = new Date() > date; //判断到期时间
      if (status) {
        tip = `<span style="color:red;">该超级会员已到期 , </span>确认退款`;
      } else if (row.status !== "3") {
        tip = "确认退款";
      }
      await this.$confirm(tip, "退款", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      });
      const res = await refundDetail(row.orderId);
      this.$message.success(res.msg);
      this.handleQuery();
    },
    // 开票记录
    recordBilling(row) {
      console.log("开票记录", row);
      this.currentRowData = row;
      this.invoiceDialog = true;
    },

    // 开始时间
    changeDatetimerange() {
      if (this.queryParamsKai) {
        this.queryParams.beBeginTime = this.queryParamsKai[0];
        this.queryParams.beEndTime = this.queryParamsKai[1];
      } else {
        this.queryParams.beBeginTime = null;
        this.queryParams.beEndTime = null;
      }
    },

    // 到期
    changeQueryParamsJie() {
      if (this.queryParamsJie) {
        this.queryParams.enBeginTime = this.queryParamsJie[0];
        this.queryParams.enEndTime = this.queryParamsJie[1];
      } else {
        this.queryParams.enBeginTime = null;
        this.queryParams.enEndTime = null;
      }
    },

    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;

      // const time = timeComparison(
      //   "earching",
      //   this.queryParams.beBeginTime,
      //   this.queryParams.beEndTime,
      //   this.queryParams.enBeginTime,
      //   this.queryParams.enEndTime
      // );
      // if (!time) return (this.loading = false);

      listDetail2(this.queryParams)
        .then((response) => {
          this.detailList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        payOrder: null,
        openingMode: null,
        enable: null,
        creatby: null,
        createdate: null,
        superId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParamsKai = null;
      this.queryParamsJie = null;
      this.queryParams.beBeginTime = null;
      this.queryParams.beEndTime = null;
      this.queryParams.enBeginTime = null;
      this.queryParams.enEndTime = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getDetail(userId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != null) {
            updateDetail(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDetail(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm(
        '是否确认删除【请填写功能名称】编号为"' + userIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delDetail(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;

      // const time = timeComparison(
      //   "export",
      //   queryParams.beBeginTime,
      //   queryParams.beEndTime,
      //   queryParams.enBeginTime,
      //   queryParams.enEndTime
      // );
      // if (!time) return;

      this.$confirm("是否确认导出所有【请填写功能名称】数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportDetail2(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    // 格式化开票状态
    invoiceStatusFotmat(row, column) {
      const types = {
        0: "未开票",
        1: "已开票",
        2: "部分开票",
        3: "不支持开票",
      };
      return types[row.invoiceStatus];
    },
  },
};
</script>
